from PySide6.QtCore import Qt
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import  QWidget, QHBoxLayout, QVBoxLayout
from qfluentwidgets import SingleDirectionScrollArea, SimpleCardWidget, CaptionLabel, MSFluentWindow, FluentIcon, NavigationItemPosition, MSFluentTitleBar, TransparentTogglePushButton
from gui.gui_qa import QAInterface
from gui.gui_subscribe import SubscribeInterface
from gui.gui_coord import CoordInterface
from gui.gui_setting import SettingInterface
from gui.gui_usercenter import UserCenterInterface
from gui.gui_disclaimer import SFormDisclaimer
from gui.gui_autotrade import AutoTradeInterface
from gui.gui_character import CharacterInterface
from core.util import loadini_annc, loadini_setting, dumpini_annc, dir_check, loadini_shotrect
from core.log import logger
import setting as c
import statement as s

def clearLayout(layout):
    # 移除旧布局中的所有小部件
    while layout.count():
        item = layout.takeAt(0)
        widget = item.widget()
        if widget:
            widget.setParent(None)
        l = item.layout()
        if l:
            clearLayout(l)

class MainInfoCard(SimpleCardWidget):
    """ App information card """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.father = parent
        
        res, ok = loadini_annc()
        if ok:
            c.annc_server = res[0]
            c.annc_sponsor = res[1]
            
        qa_shot_rect, coord_shot_rect, ok = loadini_shotrect()
        if ok:
            c.qa_shot_rect = qa_shot_rect
            c.coord_shot_rect = coord_shot_rect
        else:
            logger.warning(f"load shot rect error")
            
        self.annc_server_lb = CaptionLabel(c.annc_server)
        self.annc_server_lb.setOpenExternalLinks(True)
        self.annc_sponsor_lb = CaptionLabel(c.annc_sponsor)
        self.annc_sponsor_lb.setOpenExternalLinks(True)
        self.statement_lb = CaptionLabel(s.STATEMENT)
        self.statement_lb.setOpenExternalLinks(True)
        
        self.vBoxLayout = QVBoxLayout(self)
        self.hBoxLayout_annc_server = QHBoxLayout()
        self.hBoxLayout_annc_sponsor = QHBoxLayout()
        self.hBoxLayout_statement = QHBoxLayout()
        
        self.initLayout()

    def initLayout(self):
        self.hBoxLayout_annc_server.setSpacing(10)
        self.hBoxLayout_annc_server.setContentsMargins(5, 5, 3, 3)
        self.hBoxLayout_annc_server.addWidget(self.annc_server_lb, 1)
        
        self.hBoxLayout_annc_sponsor.setSpacing(10)
        self.hBoxLayout_annc_sponsor.setContentsMargins(5, 5, 3, 3)
        self.hBoxLayout_annc_sponsor.addWidget(self.annc_sponsor_lb, 1)
        
        self.hBoxLayout_statement.setSpacing(30)
        self.hBoxLayout_statement.setContentsMargins(5, 5, 3, 3)
        self.hBoxLayout_statement.addWidget(self.statement_lb, 1)
        
        self.vBoxLayout.addLayout(self.hBoxLayout_annc_server)
        self.vBoxLayout.addLayout(self.hBoxLayout_annc_sponsor)
        self.vBoxLayout.addLayout(self.hBoxLayout_statement)
            
    def LocateCenter(self):
        return  self.father.LocateCenter()
    
    def close(self):
        self.father.close()
        
    def show(self):
        self.annc_server_lb.setText(c.annc_server)
        self.annc_sponsor_lb.setText(c.annc_sponsor)
        
        
class MainInterface(SingleDirectionScrollArea):

    def __init__(self, parent=None):
        super().__init__(parent=None)
        self.father = parent
        self.view = QWidget(self)

        self.vBoxLayout = QVBoxLayout(self.view)
        self.mainCard = MainInfoCard(self)
        self.mainCard.setMaximumWidth(c.card_width)
        self.setWidget(self.view)
        self.setWidgetResizable(True)
        self.setObjectName('MainInterface')

        self.vBoxLayout.setSpacing(10)
        self.vBoxLayout.setContentsMargins(0, 0, 15, 0)
        self.vBoxLayout.addWidget(self.mainCard, 0, Qt.AlignTop)

        self.setStyleSheet("QScrollArea {border: none; background:transparent}")
        self.view.setStyleSheet('QWidget {background:transparent}')
        
    def show(self):
        print("show MainInterface")
        self.mainCard.show()
        
    def close(self):
        self.father.close()
        
    def LocateCenter(self):
        return  self.father.LocateCenter()
    
class TitleBar(MSFluentTitleBar):
    """ Custom title bar """

    def __init__(self, parent):
        super().__init__(parent)
        self.father = parent
        self.pinButton = TransparentTogglePushButton(self)
        self.pinButton.setIcon(FluentIcon.PIN)
        self.pinButton.setStyleSheet("""
            TransparentPushButton {
                text-align: center;
                background-color: transparent;
            }
            TransparentPushButton::icon {
                margin: 0 auto;
            }
            
        """)
        self.pinButton.setMaximumWidth(32)
        self.pinButton.clicked.connect(lambda checked=False: self.onclick_pin())
        

    def resizeEvent(self, e):
        w, h = self.width(), self.height()
        self.pinButton.move(w - 170, h//2-self.pinButton.height()//2-6)
        
    def onclick_pin(self):
        # 检查当前是否已设置窗口置顶标志
        isTopMost = self.father.windowFlags() & Qt.WindowStaysOnTopHint
        if isTopMost:
            # 取消窗口置顶
            self.father.setWindowFlag(Qt.WindowStaysOnTopHint, False)
        else:
            # 设置窗口置顶
            self.father.setWindowFlag(Qt.WindowStaysOnTopHint, True)
        # # 重新显示窗口以应用更改
        self.father.show()
        
        
class MainWindow(MSFluentWindow):

    def __init__(self, parent=None):
        super().__init__(parent)
        
        dir_check()
        
        self.setTitleBar(TitleBar(self))
        self.setWindowFlag(Qt.WindowStaysOnTopHint, True)
        self.arInterface  =[
            MainInterface(self),
            QAInterface(self),
            SubscribeInterface(self),
            CoordInterface(self),
            AutoTradeInterface(self),
            CharacterInterface(self),
            UserCenterInterface(self),
            SettingInterface(self),
        ]
        
        self.sf_disclaimer = SFormDisclaimer(self)
        self.sf_disclaimer.setModal(True)
        
        self.resize(c.win_width, c.win_height)
        self.setWindowTitle(c.WINTITLE)
        self.setWindowIcon(QIcon(c.icon_dir_path))
        
        res, ok = loadini_setting()
        if ok:
            c.URL_QA = f"http://{res[0]}:{res[1]}"
            logger.info(c.URL_QA)
            logger.info(c.URL_QA_OCR())
        ii = 0
        self.addSubInterface(self.arInterface[ii], FluentIcon.HOME,
                            '主页', selectedIcon=FluentIcon.HOME_FILL)
        ii += 1
        
        self.addSubInterface(self.arInterface[ii], FluentIcon.SEARCH,
                            '答题', selectedIcon=FluentIcon.SEARCH)
        ii += 1
        
        self.addSubInterface(self.arInterface[ii], FluentIcon.CLOUD_DOWNLOAD,
                            '订阅', selectedIcon=FluentIcon.CLOUD_DOWNLOAD)
        ii += 1
        
        self.addSubInterface(self.arInterface[ii], FluentIcon.ACCEPT_MEDIUM,
                            '坐标', selectedIcon=FluentIcon.ACCEPT_MEDIUM)
        ii += 1
        
        # self.addSubInterface(self.arInterface[ii], FluentIcon.SPEED_OFF,
        #                     '自动', selectedIcon=FluentIcon.SPEED_HIGH)
        # ii += 1
        
        self.addSubInterface(self.arInterface[ii], FluentIcon.SHOPPING_CART,
                            '估价', selectedIcon=FluentIcon.SHOPPING_CART)
        ii += 1
        
        self.addSubInterface(self.arInterface[ii], FluentIcon.PEOPLE,
                                '个人中心', selectedIcon=FluentIcon.PEOPLE,
                                position=NavigationItemPosition.BOTTOM)
        ii += 1
        
        self.addSubInterface(self.arInterface[ii], FluentIcon.SETTING,
                                '设置', selectedIcon=FluentIcon.SETTING,
                                position=NavigationItemPosition.BOTTOM)
        
        self.stackedWidget.setStyleSheet('QWidget{background: transparent}')
        
        self.stackedWidget.currentChanged.connect(self.on_current_changed)
        
    # 定义槽函数
    def on_current_changed(self, value):
        # print(f"Current changed to {value}")
        self.arInterface[value].show()
        
    def LocateCenter(self):
        return  self.frameGeometry().center()
    
    def closeEvent(self, event):
        # 调用父类的closeEvent方法，确保窗口能够正常关闭
        super().closeEvent(event)
        print("MainWindow close")
        if c.annc_server != "" or c.annc_sponsor != "":
            dumpini_annc(c.annc_server, c.annc_sponsor)
        
    def show_disclaimer(self):
        main_window_center = self.LocateCenter()
        # print(main_window_center)
        _, ok = loadini_setting()
        if ok:
            return
        # 计算主窗口中心位置
        
        new_window_geometry = self.sf_disclaimer.frameGeometry()
        new_window_geometry.moveCenter(main_window_center)
        
        # 移动新窗口到主窗口中心位置并显示
        p = new_window_geometry.topLeft()
        p.setX(p.x()-90)
        p.setY(p.y()-60)
        self.sf_disclaimer.move(p)
        self.sf_disclaimer.show()
        
    def show(self):
        super().show()
        print(f"MainWindow show")
        self.show_disclaimer()

        

        
        
    

